package com.xafc.demo.framework.execption;

import com.xafc.demo.framework.result.ApiResult;
import com.xafc.demo.framework.utils.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Object bizExceptionHandler(HttpServletRequest req, BizException e){
        logger.error("发生业务异常！原因是：" + e.getMessage(), e);
        if (RequestUtils.isAjax(req)) {
            return ApiResult.error(e.getMessage());
        }else{
            final ModelAndView mav = new ModelAndView("error");
            mav.addObject("timestamp", new Date());
            mav.addObject("exception", e);
            mav.addObject("url", req.getRequestURL());
            mav.addObject("error", "error");
            mav.addObject("status", "error");
            mav.addObject("message", "error");
            return mav;
        }
    }
}
